"""
简化的演示数据初始化命令
"""
from django.core.management.base import BaseCommand
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group, Permission
from django.db import transaction

User = get_user_model()


class Command(BaseCommand):
    help = '初始化演示数据 - 创建基本用户和角色'

    def handle(self, *args, **options):
        self.stdout.write(
            self.style.SUCCESS('🚀 开始初始化演示数据...')
        )

        with transaction.atomic():
            # 1. 创建基本角色
            self.create_basic_roles()
            
            # 2. 创建演示用户
            self.create_demo_users()
            
            # 3. 分配用户角色
            self.assign_user_roles()

        self.stdout.write(
            self.style.SUCCESS('✅ 演示数据初始化完成！')
        )
        
        self.show_user_info()

    def create_basic_roles(self):
        """创建基本角色"""
        roles_data = [
            {
                'name': '超级管理员',
                'permissions': 'all'
            },
            {
                'name': '用户管理员', 
                'permissions': ['view_user', 'add_user', 'change_user', 'delete_user']
            },
            {
                'name': '普通用户',
                'permissions': ['view_user']
            }
        ]

        for role_data in roles_data:
            group, created = Group.objects.get_or_create(
                name=role_data['name']
            )
            
            if created:
                self.stdout.write(f'✅ 创建角色: {group.name}')
            else:
                self.stdout.write(f'📋 角色已存在: {group.name}')
            
            # 分配权限
            if role_data['permissions'] == 'all':
                # 超级管理员获得所有权限
                all_permissions = Permission.objects.all()
                group.permissions.set(all_permissions)
                self.stdout.write(f'🔑 为 {group.name} 分配所有权限 ({all_permissions.count()}个)')
            else:
                # 根据权限代码分配权限
                permissions = Permission.objects.filter(
                    codename__in=role_data['permissions']
                )
                group.permissions.set(permissions)
                self.stdout.write(f'🔑 为 {group.name} 分配 {permissions.count()} 个权限')

    def create_demo_users(self):
        """创建演示用户"""
        users_data = [
            {
                'username': 'admin',
                'email': 'admin@example.com',
                'password': 'admin123',
                'is_superuser': True,
                'is_staff': True,
                'first_name': '系统',
                'last_name': '管理员'
            },
            {
                'username': 'manager',
                'email': 'manager@example.com', 
                'password': 'manager123',
                'is_superuser': False,
                'is_staff': True,
                'first_name': '用户',
                'last_name': '管理员'
            },
            {
                'username': 'user',
                'email': 'user@example.com',
                'password': 'user123',
                'is_superuser': False,
                'is_staff': False,
                'first_name': '普通',
                'last_name': '用户'
            }
        ]

        for user_data in users_data:
            user, created = User.objects.get_or_create(
                username=user_data['username'],
                defaults={
                    'email': user_data['email'],
                    'is_superuser': user_data['is_superuser'],
                    'is_staff': user_data['is_staff'],
                    'first_name': user_data['first_name'],
                    'last_name': user_data['last_name'],
                    'is_active': True
                }
            )
            
            if created:
                user.set_password(user_data['password'])
                user.save()
                self.stdout.write(f'✅ 创建用户: {user.username} ({user.email})')
            else:
                self.stdout.write(f'📋 用户已存在: {user.username}')

    def assign_user_roles(self):
        """分配用户角色"""
        role_assignments = [
            {
                'username': 'admin',
                'role_name': '超级管理员'
            },
            {
                'username': 'manager', 
                'role_name': '用户管理员'
            },
            {
                'username': 'user',
                'role_name': '普通用户'
            }
        ]

        for assignment in role_assignments:
            try:
                user = User.objects.get(username=assignment['username'])
                group = Group.objects.get(name=assignment['role_name'])
                
                # 分配角色
                user.groups.add(group)
                
                self.stdout.write(f'✅ 分配角色: {user.username} -> {group.name}')
                    
            except (User.DoesNotExist, Group.DoesNotExist) as e:
                self.stdout.write(
                    self.style.ERROR(f'❌ 角色分配失败: {assignment} - {e}')
                )

    def show_user_info(self):
        """显示用户信息"""
        self.stdout.write('\n' + '='*50)
        self.stdout.write(self.style.SUCCESS('📋 创建的用户账号信息:'))
        self.stdout.write('='*50)
        
        users = User.objects.all().order_by('is_superuser', 'username')
        for user in users:
            roles = ', '.join([group.name for group in user.groups.all()])
            self.stdout.write(
                f'👤 {user.username:10} | {user.email:20} | 角色: {roles or "无"}'
            )
            
        self.stdout.write('='*50)
        self.stdout.write('🔑 默认密码规则:')
        self.stdout.write('   - admin: admin123')
        self.stdout.write('   - manager: manager123') 
        self.stdout.write('   - user: user123')
        self.stdout.write('='*50)
